package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.article.dto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 文章图片审核
 */
@Transactional
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 自媒体文章审核
     * @param id  自媒体文章id
     */
    @Override
    @Async //标注当前方法是一个异步方法
    public void autoScanWmNews(Integer id)  {
        if(id==null){
            throw new RuntimeException("参数无效");
        }
//        查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(StringUtils.isEmpty(wmNews)){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
//        从内容中提取纯文本内容和图片
        Map<String,Object> textImages=handTextImages(wmNews);
//        审核文本内容   阿里云接口
       boolean isText= handText((String) textImages.get("content"),wmNews);
       if(!isText){
           return;
       }
//       自管理文章敏感词审核
       boolean isSensitive=handSensitive((String) textImages.get("content"),wmNews);
       if(!isSensitive){
           return;
       }
//        //3.审核图片  阿里云接口
//        boolean isImageScan =  handleImageScan((List<String>) textImages.get("images"),wmNews);
//        if(!isImageScan){
//            return;
//        }
        //4.审核成功，保存app端的相关的文章数据
        ResponseResult responseResult = saveAppArticle(wmNews);
        if(responseResult.getCode()!=200){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
        }
        //回填article_id
        wmNews.setArticleId((Long) responseResult.getData());
        wmNews.setStatus((short)9);
        wmNews.setReason("审核成功");
        wmNewsMapper.updateById(wmNews);

    }

    /**
     * 自管理的敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    private boolean handSensitive(String content, WmNews wmNews) {
//        查询所有敏感词
        List<WmSensitive> sensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitive = sensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
//        初始化敏感词库
        SensitiveWordUtil.initMap(sensitive);
//        查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
       if(map.size()>0){
           wmNews.setStatus((short)2);
           wmNews.setReason("当前文章中存在违规内容-"+map);
           wmNewsMapper.updateById(wmNews);
           return false;
       }
       return true;
    }

    /**
     * 保存app端相关的文章数据
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
//        降级测试
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        ArticleDto articleDto = new ArticleDto();
//        属性拷贝
        BeanUtils.copyProperties(wmNews,articleDto);
//        文章的布局
        articleDto.setLayout(wmNews.getType());
//        频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(!StringUtils.isEmpty(wmChannel)){
            articleDto.setChannelName(wmChannel.getName());
        }
//        作者
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(!StringUtils.isEmpty(wmUser)){
            articleDto.setAuthorName(wmUser.getName());
        }
//        设置文章id
        if(wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(articleDto);
        return responseResult;

    }

    /**
     * 审核图片内容
     * @param
     * @param wmNews
     * @return
     */
    @Autowired
    private Tess4jClient tess4jClient;
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag=true;
        if(images.size()==0||images==null){
            return flag;
        }
//        minio下载图片
//        去重
        images = images.stream().distinct().collect(Collectors.toList());
        ArrayList<byte[]> bytes = new ArrayList<>();
        for (String image : images) {
            try {
                byte[] downLoadFile = fileStorageService.downLoadFile(image);
                //            从byte[]转换成ButteredImage
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(downLoadFile);
                BufferedImage imageFile = ImageIO.read(byteArrayInputStream);
//                图片文字识别
                String resilt = tess4jClient.doOCR(imageFile);
//                审核是否包含敏感词
                boolean b = handText(resilt, wmNews);
                if(!b){
                    return b;
                }
                bytes.add(downLoadFile);
            } catch (IOException | TesseractException e) {
                e.printStackTrace();
            }
        }
//        审核图片
        try {
            Map map = greenImageScan.imageScan(bytes);
            if(map!=null){
//                审核失败
                if(map.get("suggestion").equals("block")){
                    flag=false;
                    wmNews.setStatus((short)2);
                    wmNews.setReason("图片审核失败");
                    wmNewsMapper.updateById(wmNews);
                }
//                不确定内容，需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag=false;
                    wmNews.setStatus((short)3);
                    wmNews.setReason("当前文章中存在不确定内容");
                    wmNewsMapper.updateById(wmNews);
                }
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 审核文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handText(String content, WmNews wmNews)  {
        boolean flag=true;
        if(content.length()==0){
            if(wmNews.getTitle().length()==0){
                return flag;
            }
        }

        try {
            Map map = greenTextScan.greeTextScan(wmNews.getTitle() + "-" + content);
            if(map!=null){
//            审核失败
                if(map.get("suggestion").equals("block")){
                    flag=false;
                    wmNews.setStatus((short)2);
                    wmNews.setReason("文章内容审核失败");
                    wmNewsMapper.updateById(wmNews);
                }
//                不确定信息，需要人工审核
                if(map.get("suggestion").equals("review")){
                    flag=false;
                    wmNews.setStatus((short)3);
                    wmNews.setReason("文章内容中有不确定内容，需要人工审核");
                    wmNewsMapper.updateById(wmNews);
                }
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 1。从自媒体文章的内容中提取文本和图片
     * 2.提取文章的封面图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handTextImages(WmNews wmNews) {
//        储存纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        ArrayList<String> arrayList = new ArrayList<>();
//        从文章中内容提取图片
        if(org.apache.commons.lang3.StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                if(map.get("type").equals("text")) {
                    stringBuilder.append(map.get("value"));
                }
                if(map.get("type").equals("image")){
                    arrayList.add(map.get("value").toString());
                }
            }
        }
//        提取文章封面的图片
        if(!StringUtils.isEmpty(wmNews.getImages())){
            String[] split = wmNews.getImages().split(",");
            arrayList.addAll(Arrays.asList(split));
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content",stringBuilder.toString());
        hashMap.put("images",arrayList);
        return hashMap;
    }
}
